#include <iostream>
#include <vector>
#include <string>

using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

ListNode *removeElements(ListNode *head, int val)
{
    while (head != nullptr &&head->val == val)
    {
        ListNode *t = head;
        head = head->next;
        delete t;
    }
    ListNode *p = head, *q = p != nullptr ? p->next : p;
    while (q != nullptr)
    {
        if (q->val == val)
        {
            ListNode *t = q;
            p->next = q->next;
            delete t;
        }else
        {
            p = q;
        }
        q = p->next;
    }
    return head;
}

int main()
{
    int val = 6;
    ListNode node6(6), node5(5, &node6), node4(4, &node5), node3(3, &node4), node2(6, &node3), node1(2, &node2), head(1, &node1);
    ListNode *r = removeElements(&head, val);
    while (r != nullptr)
    {
        cout << r->val << endl;
        r = r->next;
    }
    return 0;
}
